package com.guc.coroutines.fg

import android.os.Bundle
import android.view.*
import androidx.fragment.app.Fragment
import androidx.fragment.app.commit
import com.guc.coroutines.FragmentDemoActivity
import com.guc.coroutines.R
import com.guc.coroutines.databinding.ActivityMainBinding
import com.guc.coroutines.databinding.FragmentFirstBinding
import com.guc.gviewbinding.bindView
import com.guc.gviewbinding.inflate

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * A simple [Fragment] subclass.
 * Use the [FirstFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class FirstFragment : Fragment(R.layout.fragment_first) {
    // TODO: Rename and change types of parameters
    private var param1: String? = null
    private var param2: String? = null
    private val mainBinding: FragmentFirstBinding by bindView()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setHasOptionsMenu(false)
        arguments?.let {
            param1 = it.getString(ARG_PARAM1)
            param2 = it.getString(ARG_PARAM2)
        }
    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        inflater.inflate(R.menu.database_menu,menu)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mainBinding.tvShow.text = param1.plus(param2)
        mainBinding.btnNext.setOnClickListener {
            if (activity is FragmentDemoActivity) {
                (activity as FragmentDemoActivity).apply {
                    supportFragmentManager.commit {
                        setReorderingAllowed(true)
                        addToBackStack(null)
                        add(R.id.fragment_container, SecondFragment.newInstance("1","2"))
                    }
                }
            }
        }
    }

    companion object {
        @JvmStatic
        fun newInstance(param1: String, param2: String) =
            FirstFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_PARAM1, param1)
                    putString(ARG_PARAM2, param2)
                }
            }
    }
}